import { request } from '../../request/index'
var { formatTime } = require('../../utils/Time')
//消息协议
var SocketMessage = require('../../utils/SocketMessage')
import TimeShow from '../../utils/TimeShow'
import forMate from '../../utils/timeLocal'
Page({
  data: {
    isHave: false,
    message: '',
    keybordHeight: 0,
    num: {},
    tishi: '评论',
    ps: [],
    userId: null,

    // 礼物展示
    liShow: false,
    liId: 0,
    // 被选中的按钮
    xid: 1,
    // 礼物榜单信息
    tuhao: [],

    // 是否是评论楼主
    isLou: true,

    userInfo: {},

    // 评论人id
    id: 0,

    // 被评论人的id
    bid: 0,

    //input聚焦
    isFouse: false,

    giftNum: 1,
    Top3: []
  },
  pid: null,

  qtype: 0,

  userInfo: null,

  onLoad: function (options) {
    this.qtype = options.type
    this.userInfo = wx.getStorageSync('userInfo')
    this.setData(
      {
        num: JSON.parse(options.num),
        bid: JSON.parse(options.num).userid,
        userInfo: wx.getStorageSync('userInfo'),
        userId: wx.getStorageSync('userId')
      },
      () => {
        this.setPs()
      }
    )
    this.getWinddow()
    this.getGift(true)

    this.addView()
  },

  // 输入框值
  bindKeyInput(e) {
    if (e.detail.value != '') {
      this.setData({
        isHave: true,
        message: e.detail.value
      })
    } else {
      this.setData({
        isHave: false
      })
    }
  },
  // 获取键盘高
  getWinddow() {
    wx.onKeyboardHeightChange((res) => {
      if (this.data.keybordHeight != res.height) {
        this.setData({
          keybordHeight: res.height
        })
      }

      if (res.height === 0) {
        this.setData({
          tishi: '评论'
        })
      }
    })
  },

  //点赞
  async handChang() {
    let { num } = this.data
    let dian = wx.getStorageSync('dian')
    if (!dian) dian = []
    const dianData = {
      postId: num.id,
      uId: this.data.userId,
      cTime: formatTime(new Date())
    }
    const { data } = await request({
      url: `/like/${JSON.stringify(dianData)}/${this.qtype}`,
      method: 'post'
    })
    if (data.state == 1) {
      num.isClick = true
      dian.push(num.id)
      wx.setStorageSync('dian', dian)
      num.likeNum += 1
      const dainData = {
        userId: this.data.userId,
        chatId: num.userid,
        message: `${this.userInfo.nickName}赞了你`,
        messageType: SocketMessage.GREAT,
        stime: formatTime(new Date())
      }
      wx.sendSocketMessage({
        data: JSON.stringify(dainData)
      })
    }
    if (data.state == 2) {
      num.likeNum -= 1
      num.isClick = false
      dian.some((item, i) => {
        if (item == num.id) {
          dian.splice(i, 1)
          return true
        }
      })
      wx.setStorageSync('dian', dian)
    }
    this.setData({
      num
    })
  },

  // 第一级评论
  handPL(e) {
    const { id, ss } = e.currentTarget.dataset
    this.setData({
      liShow: false,
      xid: 1,
      bid: id,
      tishi: '评论',
      isLou: true
    })
    if(ss != 0) {
      console.log(ss)
      this.setData({
        isFouse: true
      })
    }
  },
  // 第二级评论
  handPer(e) {
    const { id, pid } = e.currentTarget.dataset
    this.pid = pid
    this.setData({
      liShow: false,
      bid: id,
      tishi: `回复${this.finUser(id).uname}`,
      isFouse: true,
      isLou: false
    })
  },

  // 送礼
  handSong() {
    this.setData({
      isFouse: false,
      liShow: true
    })
  },
  handSetNUm(e) {
    const { gift } = e.currentTarget.dataset
    if (gift) {
      this.setData({
        giftNum: this.data.giftNum + 1
      })
    } else if (this.data.giftNum > 1) {
      this.setData({
        giftNum: this.data.giftNum - 1
      })
    }
  },
  handCacle() {
    this.setData({
      isFouse: false,
      liShow: false
    })
  },
  handHaha(e) {
    this.setData({
      giftNum: 1,
      liId: e.currentTarget.dataset.liid
    })
  },
  async shongLi() {
    if (this.data.liId === 0) {
      wx.showToast({
        title: '请选择礼物',
        icon: 'error',
        duration: 2000
      })
      return
    }
    const { avatarUrl } = this.data.userInfo
    const ss = avatarUrl.split('/')
    let uHead = ''
    ss.forEach((value) => {
      if (uHead === '') {
        uHead = value
      } else {
        uHead += `xd728${value}`
      }
    })
    const gitData = {
      postId: this.data.num.id,
      uId: this.data.userId,
      uName: this.data.userInfo.nickName,
      uHead,
      sTime: formatTime(new Date()),
      giftNum: this.data.giftNum
    }
    const { data } = await request({
      url: `/GiftTo/${JSON.stringify(gitData)}`,
      method: 'post'
    })
    console.log(data)
    if (data.state == 0) {
      wx.showToast({
        title: '送礼失败',
        icon: 'error',
        duration: 2000
      })
    } else {
      wx.showToast({
        title: '成功送礼',
        icon: 'success',
        duration: 2000
      })
      const lidata = {
        userId: this.data.userId,
        chatId: this.data.num.userid,
        message: `${this.userInfo.nickName}给你送了个礼物`,
        messageType: 6,
        stime: formatTime(new Date())
      }
      wx.sendSocketMessage({
        data: JSON.stringify(lidata)
      })
    }
  },
  handZhu() {},

  // 发送评论信息
  async fasong() {
    let { ps } = this.data
    const { avatarUrl } = this.userInfo
    const ss = avatarUrl.split('/')
    let uheadpic = ''
    ss.forEach((value) => {
      if (uheadpic === '') {
        uheadpic = value
      } else {
        uheadpic += `xd728${value}`
      }
    })
    let comment = {
      id: `${this.data.userId}${forMate()}`, //评论者
      postId: `${this.data.num.id}`, //墙的id
      uId: this.data.userId, //发布者
      uname: this.userInfo.nickName, //发布者nickname
      uheadpic, //发布者头像
      usex: this.userInfo.gender, //发布者性别
      u2Id: this.data.bid, //上一级id
      content: this.data.message, //评论类内容
      stime: formatTime(new Date()) //评论时间
    }
    const { data: res } = await request({
      url: `/comment/${JSON.stringify(comment)}`,
      method: 'post'
    })
    if (res.state === 0) {
      wx.showToast({
        title: '网络开小差了',
        icon: 'error',
        duration: 1500,
        mask: true
      })
      return
    }
    // 通知被评论人
    const webData = {
      userId: this.data.userId,
      chatId: this.data.bid,
      message: this.data.message,
      messageType: SocketMessage.REVIEW,
      stime: formatTime(new Date())
    }
    wx.sendSocketMessage({
      data: JSON.stringify(webData),
      success: (r) => {
        console.log('cg', r)
      },
      fail: (e) => {
        console.log(e)
      }
    })
    const times = forMate()
    comment['uheadpic'] = avatarUrl
    comment['bottonid'] = `it${times}`
    comment['stime'] = TimeShow(comment['stime'])
    if (this.data.isLou) {
      ps.push(comment)
    } else {
      ps.some((item) => {
        if (item.uid === comment['u2Id']) {
          comment['toname'] = item['uname']
          if (!item['i']) item['i'] = []
          item['i'].push(comment)
          return true
        }
        if (item['i']) {
          item.i.some((arr) => {
            if (arr.uid === comment['u2Id']) {
              comment['toname'] = arr['uname']
              item['i'].push(comment)
              return true
            }
          })
        }
      })
    }
    this.setData({
      ps,
      message: '',
      isHave: false,
      isFouse: false,
      tishi: '评论',
      bottonid: `it${times}`
    })
  },

  //预览图片或视频
  handYu(e) {
    const { index } = e.currentTarget.dataset
    wx.previewImage({
      current: index,
      urls: this.data.num.imgs
    })
  },

  // 寻找被回复人的信息
  finUser(id) {
    const { ps } = this.data
    let child = {}
    ps.some((item) => {
      if (item.uid === id) {
        child = item
        return true
      }
      if (item['i']) {
        item.i.some((arr) => {
          if (arr.uid === id) {
            child = arr
            return true
          }
        })
      }
    })
    return child
  },

  async handXuan(e) {
    if (e.currentTarget.dataset.xid == 3) {
      this.getGift(false)
    }
    this.setData({
      xid: e.currentTarget.dataset.xid
    })
  },

  handUser(e) {
    const { userid, username } = e.currentTarget.dataset
    console.log(userid, username)
    wx.navigateTo({
      url: `/pages/personal/personal?userId=${userid}&username=${username}`
    })
  },

  // 渲染
  async setPs() {
    let { data: res } = await request({
      url: `/comments0/${this.data.num.id}`,
      method: 'post'
    })
    console.log(res)
    res.forEach((item) => {
      let uheadpic = ''
      const ss = item['uheadpic'].split('xd728')
      ss.forEach((value) => {
        if (uheadpic === '') {
          uheadpic = value
        } else {
          uheadpic += `/${value}`
        }
      })
      item['uheadpic'] = uheadpic
      item['stime'] = TimeShow(item['stime'])
    })
    res.forEach((item, index) => {
      if (item.u2Id !== item.uid) {
        res.some((it) => {
          if (it.uid === item.u2Id) {
            item['toname'] = it.uname
            if (!it['i']) it['i'] = []
            it['i'].push(item)
            res.splice(index, 1)
            return true
          }
          if (it['i']) {
            it['i'].some((arr) => {
              if (arr.uid === item.u2Id) {
                item['toname'] = arr.uname
                it['i'].push(item)
                res.splice(index, 1)
                return true
              }
            })
          }
        })
      }
    })
    // console.log(res)
    this.setData({
      ps: res
    })
  },
  // 获得礼物排行榜
  async getGift(isFirst) {
    const { data: res } = await request({
      url: `/GiftPHB/${this.data.num.id}`
    })
    if (res.state === 1) {
      let { tuhao } = res
      tuhao.forEach((item) => {
        const imgs = item.uHead.split('xd728')
        let uHead = ''
        imgs.forEach((value, index) => {
          // if(index < (imgs.length-1)) {
          if (uHead === '') {
            uHead = value
          } else {
            uHead += '/' + value
          }
          // }
        })
        item.uHead = uHead
      })
      let { Top3 } = this.data
      if(isFirst) {
        tuhao.forEach((item, index) => {
          if (index <= 2) {
            Top3.push(item)
          }
        })
      }
      this.setData({
        tuhao,
        Top3
      })
    }
  },

  // 增加浏览记录
  async addView() {
    const { data } = await request({
      url: `/viewnum/${this.qtype}/${this.data.num.id}`,
      method: 'post'
    })
    console.log(data)
  }
})
